<template />

<script>
import $sr from '@/utils/x-sr';

export default {
  name: 'TransitPay',
  components: {},
  props: {},
  data() {
    return {
      query: {},
      payOrderInfo: null
    };
  },
  computed: {},
  watch: {},
  onLoad(query) {
    this.query = query;
  },
  async onShow(options) {
    const {
      masterAppId,
      masterOpenId,
      masterUnionId
    } = this.query;
    await this.$store.dispatch('user/login', {
      masterAppId,
      masterOpenId,
      masterUnionId
    });
    if (this.query.paramsId || this.query.type) {
      this.getOrderInfo();
    }
  },
  onHide() {
    // 离开中转页后，状态改为2，避免商品页逻辑出错，导致退不出去
    this.query = null;
  },
  methods: {
    getOrderInfo() {
      const params = {
        paramsId: this.query.paramsId
      };
      console.log(111111, this.query);
      // 如果是重新支付
      if (this.query.type === 'repay') {
        const repayParams = {
          ...this.query,
          orderId: this.query.orderId,
          incidentallyOrderId: this.query.incidentallyOrderId,
          preferentialAmount: this.query.payCancelPopDiscountAmount || 0,
          refluxType: this.query.refluxType
        };
        this.$http({
          login: true,
          url: '/order/order/repay',
          method: 'post',
          data: repayParams,
          alarm: true
        }).then(res => {
          const wxParams = res.data;
          this.payOrderInfo = res.data;
          // 有数上报，支付
          this.srTrack('pay');
          uni.requestPayment({
            orderInfo: wxParams.orderInfo,
            timeStamp: wxParams.timeStamp,
            paySign: wxParams.paySign,
            nonceStr: wxParams.nonceStr,
            signType: wxParams.signType,
            package: wxParams.package,
            success: () => {
              this.srTrack('payed');
              this.$XTrack('orderPaySuccess', Object.assign(this.payOrderInfo, {
                isRepay: true,
                preferentialAmount: this.payCancelPopDiscountAmount
              }));
              wx.navigateBackMiniProgram({
                extraData: {
                  orderId: wxParams.orderId,
                  payStatus: 1
                },
                success(res) {
                  console.log(res);
                },
                fail(res) {
                  console.log(res);
                }
              });
            },
            fail: (err) => {
              try {
                this.$XTrack('errorOrderPay', err.errMsg);
                if (err.errMsg.includes('cancel')) {
                  this.$http({
                    login: true,
                    url: '/order/order/params',
                    method: 'post',
                    data: { json: wxParams },
                    alarm: true
                  }).then(res => {
                    try {
                      wx.navigateBackMiniProgram({
                        extraData: {
                          orderId: wxParams.orderId,
                          handleCancelPayPop: 1,
                          paramsId: res.data
                        },
                        success(res) {
                          console.log(res);
                        },
                        fail(res) {
                          console.log(res);
                        }
                      });
                    } catch (e) {
                      this.clickStatus = true;
                      console.log(e);
                    }
                  });
                  // this.handleCancelPayPop();
                  // 有数上报，取消支付
                  this.srTrack('cancel_pay');
                }
              } catch (e) { console.log(e); }
            },
            complete: () => {
              this.loading = false;
            }
          });
        }).catch(err => {
          this.loading = false;
          console.log(err);
        });
        return;
      }
      this.$http({
        login: true,
        url: '/order/order/params',
        method: 'GET',
        data: params,
        alarm: true
      }).then(res => {
        const data = res.data;
        if (data) {
          const newParams = JSON.parse(data);
          this.$http({
            login: true,
            url: '/order/order/asymmetric/save',
            method: 'post',
            data: newParams.order,
            alarm: true
          }).then(res => {
            const wxParams = res.data;
            this.payOrderInfo = res.data;
            this.clickStatus = true;
            this.srTrack('give_order');
            this.$XTrack('orderSuccessInfo', {
              pageId: wxParams.pageId,
              productId: wxParams.productId,
              orderId: res.data.orderId,
              couponInfo: wxParams.userSelectCoupon,
              discountAmount: wxParams.discountAmount
            });
            uni.requestPayment({
              orderInfo: wxParams.orderInfo,
              timeStamp: wxParams.timeStamp,
              paySign: wxParams.paySign,
              nonceStr: wxParams.nonceStr,
              signType: wxParams.signType,
              package: wxParams.package,
              success: () => {
                this.srTrack('payed');

                // 埋点
                this.$XTrack('orderPaySuccess', {
                  pageId: wxParams.pageId,
                  productId: wxParams.productId,
                  orderId: res.data.orderId,
                  couponInfo: wxParams.userSelectCoupon,
                  discountAmount: wxParams.discountAmount
                });
                this.$store.dispatch('message/requestSubscribeMessage', {
                  subscribeNode: 1,
                  subscribeType: 1,
                  subscribeContent: wxParams.pageId,
                  storeId: wxParams.storeId
                }).then(() => {
                  // 如果是半屏小程序下单，并且是从主小程序进来
                  wx.navigateBackMiniProgram({
                    extraData: {
                      orderId: wxParams.orderId,
                      payStatus: 1 // 1支付完成
                    },
                    success(res) {
                      console.log(res);
                    },
                    fail(res) {
                      console.log(res);
                    },
                    complete(res) {
                      console.log(res);
                    }
                  });
                }).catch(() => {
                  // 如果是半屏小程序下单，并且是从主小程序进来
                  wx.navigateBackMiniProgram({
                    extraData: {
                      orderId: wxParams.orderId,
                      payStatus: 1 // 1支付完成
                    },
                    success(res) {
                      console.log(res);
                    },
                    fail(res) {
                      console.log(res);
                    },
                    complete(res) {
                      console.log(res);
                    }
                  });
                });
              },
              fail: (err) => {
                // console.log(err);
                this.clickStatus = true;
                this.$http({
                  login: true,
                  url: '/order/order/params',
                  method: 'post',
                  data: { json: wxParams },
                  alarm: true
                }).then(res => {
                  try {
                    this.$XTrack('errorOrderPay', err.errMsg);
                    if (err.errMsg.includes('cancel')) {
                      this.$XTrack('cancelOrderPay', wxParams);
                      if (newParams.json) {
                        console.log(newParams.json.payCancelPopDiscountAmount, newParams.json.discountAmount, '取消支付', newParams);
                        // 如果当前已经是最大优惠了，那么不显示下单未支持弹层
                        // 使用优惠券的场景下，不显示下单未支持弹层
                        if (newParams.json.payCancelPopDiscountAmount > newParams.json.discountAmount || 0) {
                          // this.payCancelTwoVisible = true;
                          // // 取消支付，可以使用优惠金额支付了
                          // this.repay = true;
                          // 如果是半屏小程序下单，并且是从主小程序进来
                          wx.navigateBackMiniProgram({
                            extraData: {
                              orderId: wxParams.orderId,
                              payCancelTwoVisible: 1,
                              repay: 1,
                              paramsId: res.data
                            },
                            success(res) {
                              console.log(res);
                            },
                            fail(res) {
                              console.log(res);
                            }
                          });
                        } else {
                          wx.navigateBackMiniProgram({
                            extraData: {
                              orderId: wxParams.orderId,
                              payCancelVisible: 1,
                              paramsId: res.data
                            },
                            success(res) {
                              console.log(res);
                            },
                            fail(res) {
                              console.log(res);
                            }
                          });
                          // this.payCancelVisible = true;
                        }
                      } else {
                        wx.navigateBackMiniProgram({
                          extraData: {
                            orderId: wxParams.orderId,
                            payCancelVisible: 1,
                            paramsId: res.data
                          },
                          success(res) {
                            console.log(res);
                          },
                          fail(res) {
                            console.log(res);
                          }
                        });
                      }
                      // 有数上报，取消支付
                      this.srTrack('cancel_pay');
                    }
                  } catch (e) {
                    this.clickStatus = true;
                    console.log(e);
                  }
                });
              },
              complete: () => {
                this.loading = false;
              }
            });
          });
        }
      });
    },
    // 有数上报
    // give_order：用户提交订单；
    // pay：用户发起支付；
    // cancel_pay：用户关闭支付密码浮层；
    // payed：用户完成支付（影响有数实时订单统计）；
    // cancel_give_order：用户取消订单；
    // refund：用户发起退货退款
    srTrack(status) {
      try {
        const { orderInfo } = this.payOrderInfo;
        const { price_info, product_infos } = orderInfo.order_detail;

        // 优惠前的商品总价
        let orderAmt = 0;
        product_infos.forEach(item => {
          orderAmt += (item.sale_price * item.product_cnt);
        });
        $sr.track('custom_order', {
          'order': {
            'order_id': orderInfo.out_order_id,
            'order_time': +new Date(orderInfo.create_time.replace(/-/gi, '/')),
            'order_status': status
          },
          'sub_orders': [{
            'sub_order_id': orderInfo.out_order_id,
            'order_amt': this.$tools.formatNumber(orderAmt / 100),
            'pay_amt': this.$tools.formatNumber(price_info.order_price / 100)
          }]
        });
      } catch (e) {
        console.log('srTrack->', e);
      }
    }
  }
};
</script>

<style>

</style>
